package sc.digital.human;

import com.google.gson.Gson;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Vop {
    private static final Logger logger = LoggerFactory.getLogger(Vop.class);
    private final OkHttpClient httpClient = new OkHttpClient.Builder().build();
    private final Gson gson = new Gson();

    public Vop() {
    }

    /**
     * 语音识别
     *
     * @param token    Token
     * @param buffer   语音
     * @param callback 回调
     */
    public void asr(Token token, byte[] buffer, Callback callback) {
        token.refresh((credentials) -> {
            if (credentials == null) {
                callback.result(null);
            } else {
                this.httpClient.newCall(new Request.Builder()
                        .header("format", "pcm")
                        .header("rate", String.valueOf(Config.SAMPLE_RATE))
                        .post(RequestBody.create(MediaType.parse("audio/pcm;rate=" + Config.SAMPLE_RATE), buffer))
                        .url(String.format(Config.ASR_URL, credentials.access_token))
                        .build()).enqueue(new okhttp3.Callback() {
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (logger.isInfoEnabled()) {
                            logger.info("语音识别：{}", response);
                        }
                        if (!response.isSuccessful() || response.body() == null) {
                            callback.result(null);
                        } else {
                            String json = response.body().string();
                            if (logger.isInfoEnabled()) {
                                logger.info("语音识别：{}", json);
                            }
                            Result result = gson.fromJson(json, Result.class);
                            callback.result(result.isSuccess() ? result.result[0] : null);
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        if (logger.isErrorEnabled()) {
                            logger.error("语音识别：{}", e, e);
                        }
                        callback.result(null);
                    }
                });
            }
        });
    }

    interface Callback {
        /**
         * 获取语音识别结果
         *
         * @param result 语音识别结果
         */
        void result(String result);
    }

    static class Result {
        public int err_no;
        public String[] result;

        public boolean isSuccess() {
            return 0 == err_no
                    && result != null
                    && result.length > 0;
        }
    }
}
